const fs = require('fs')
const path = require('path')
const copydir = require('copy-dir')
const { prompt } = require('inquirer')

const resolve = (file) => path.resolve(__dirname, file)
const updateEntries = (entry, name, port) => {
  const file = resolve('./build/config.entries.json')
  const apps = JSON.parse(fs.readFileSync(file, 'utf-8'))
  apps.push({ value: entry, name, port })
  fs.writeFileSync(file, JSON.stringify(apps, null, 2), 'utf-8')
}

const updateAppsJs = (entry, port) => {
  const file = resolve('./src/pages/master/apps.js')
  let apps = fs.readFileSync(file, 'utf-8')
  apps = apps.replace('  // app placeholder', `  { name: '${entry}', port: ${port} },\n  // app placeholder`)
  fs.writeFileSync(file, apps, 'utf-8')
}

prompt([
  { type: 'input', name: 'entry', message: '输入要创建的模块英文名称：' },
  { type: 'input', name: 'name', message: '请输入模块中文名称：' },
]).then((answers) => {
  const { entry, name } = answers
  if (!entry && !name) return

  let entries = resolve('./build/config.entries.json')
  entries = JSON.parse(fs.readFileSync(entries, 'utf-8'))
  const port = entries[entries.length - 1].port + 1

  updateEntries(entry, name, port)
  updateAppsJs(entry, port)

  const entryDir = resolve(`./src/pages/${entry}`)
  copydir(resolve('./template'), entryDir, {
    utimes: true,
    mode: true,
    cover: true,
  })
})
